import React, { useState } from 'react';
import { Form, Input, Button, Card, message, Typography, Space } from 'antd';
import { UserOutlined, LockOutlined, MailOutlined, HomeOutlined } from '@ant-design/icons';
import { useNavigate, Link } from 'react-router-dom';
import { useUserStore } from '../../store/userStore';
import axios from 'axios';

const { Title, Text } = Typography;

const Login: React.FC = () => {
  const [loading, setLoading] = useState(false);
  const navigate = useNavigate();
  const { login } = useUserStore();

  // const onFinish = async (values: { email: string; password: string }) => {
  //   try {
  //     setLoading(true);
  //     const response = await fetch('http://127.0.0.1:3000/api/auth/login', {
  //       method: 'POST',
  //       headers: {
  //         'Content-Type': 'application/json',
  //       },
  //       body: JSON.stringify(values),
  //     });

  //     const data = await response.json();

  //     if (!response.ok) {
  //       throw new Error(data.message || '登录失败');
  //     }

  //     // 确保用户数据包含所有必要字段
  //     const userData = {
  //       ...data.user,
  //       carbonFootprint: data.user.carbonFootprint || 25,
  //       greenEnergy: data.user.greenEnergy || 100,
  //       achievements: data.user.achievements || [],
  //       tasks: data.user.tasks || [],
  //       planetState: {
  //         pollution: data.user.planetState?.pollution || 30,
  //         biodiversity: data.user.planetState?.biodiversity || 70,
  //         energy: {
  //           clean: data.user.planetState?.energy?.clean || 30,
  //           total: data.user.planetState?.energy?.total || 100
  //         },
  //         buildings: data.user.planetState?.buildings || [],
  //         trees: data.user.planetState?.trees || 100,
  //         waterQuality: data.user.planetState?.waterQuality || 80
  //       }
  //     };

  //     login(data.token, userData);
  //     message.success('登录成功！');
  //     navigate('/dashboard/planet');
  //   } catch (error: any) {
  //     message.error(error.message || '登录失败，请重试');
  //   } finally {
  //     setLoading(false);
  //   }
  // };
  const onFinish = async (values: { email: string; password: string }) => {
    try {
      setLoading(true);
      const response = await axios.post('http://127.0.0.1:3000/api/auth/login', {
        email: values.email,
        password: values.password
      });

      const { token, user } = response.data;
      localStorage.setItem('userId', user._id);
      login(token, user);
      message.success('登录成功！');
      navigate('/dashboard/planet');
    } catch (error: any) {
      message.error(error.response?.data?.message || '登录失败，请重试');
    } finally {
      setLoading(false);
    }
  };

  return (
    <div style={{ 
      minHeight: '100vh',
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      background: 'linear-gradient(135deg, #f5f7fa 0%, #c3cfe2 100%)',
      position: 'relative'
    }}>
      <Button 
        type="link" 
        icon={<HomeOutlined />}
        style={{ 
          position: 'absolute',
          top: '20px',
          left: '20px',
          color: '#1a5f7a',
          fontSize: '16px',
          fontWeight: 'bold'
        }}
        onClick={() => navigate('/')}
      >
        返回首页
      </Button>
      
      <Card style={{ 
        width: 400,
        padding: '20px',
        boxShadow: '0 4px 6px rgba(0, 0, 0, 0.1)',
        borderRadius: '15px'
      }}>
        <Space direction="vertical" size="large" style={{ width: '100%' }}>
          <div style={{ textAlign: 'center' }}>
            <Title level={2} style={{ color: '#2E8B57', marginBottom: 0 }}>
              欢迎回来
            </Title>
            <Text type="secondary">
              登录您的碳星球账号
            </Text>
          </div>

          <Form
            name="login"
            onFinish={onFinish}
            layout="vertical"
            size="large"
          >
            <Form.Item
              name="email"
              rules={[
                { required: true, message: '请输入邮箱' },
                { type: 'email', message: '请输入有效的邮箱地址' }
              ]}
            >
              <Input 
                prefix={<MailOutlined />} 
                placeholder="邮箱"
              />
            </Form.Item>

            <Form.Item
              name="password"
              rules={[{ required: true, message: '请输入密码' }]}
            >
              <Input.Password
                prefix={<LockOutlined />}
                placeholder="密码"
              />
            </Form.Item>

            <Form.Item>
              <Button 
                type="primary" 
                htmlType="submit" 
                loading={loading}
                style={{ 
                  width: '100%',
                  height: '40px',
                  background: '#2E8B57',
                  borderColor: '#2E8B57'
                }}
              >
                登录
              </Button>
            </Form.Item>
          </Form>

          <div style={{ textAlign: 'center' }}>
            <Text type="secondary">
              还没有账号？ <Link to="/register" style={{ color: '#2E8B57' }}>立即注册</Link>
            </Text>
          </div>
        </Space>
      </Card>
    </div>
  );
};

export default Login; 